package NW_MC;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import NWPackage.PairPreferdCandidateCell;
import Readers.InputsReader;
//import Readers.StaticInputs;
//import Readers.StaticInputs3cands;

public class AgentsMinMaxMatrix {

	//<Agent, Candidate - Min/Max>
	private Map<String,CandidateMinMax> agentsMinMax;
	
	//<Candidate, Max Sum>
	private Map<String,Integer> candidatesMaxSum;
	
	//<Candidate,Min Sum>
	private Map<String,Integer> candidatesMinSum;
	
	
	
	public AgentsMinMaxMatrix()
	{
		candidatesMaxSum = new HashMap<String, Integer>();
		candidatesMinSum = new HashMap<String, Integer>();
	}

	public void InitialAgentsMatrix(List<String> optionalWinners) {
		String[] agents = InputsReader.getAgents();
		
		Map<String,CandidateMinMax> agentsMinMax = new HashMap<String, CandidateMinMax>();
		for (String agent : agents) {
			agentsMinMax.put(agent, new CandidateMinMax(optionalWinners));
			
		}
		this.agentsMinMax = agentsMinMax;
		
	}

	public void setQueriesMinMax(List<PairPreferdCandidateCell> moreQueries) {
		for (PairPreferdCandidateCell query : moreQueries) {
			agentsMinMax.get(query.getAgentName()).setQuery(query);
		}
		
	}

	public void calcSumMinMax(List<String> optionalWinners) {
		MinMaxCell minMaxCell;
		candidatesMaxSum = new HashMap<String, Integer>();
		candidatesMinSum = new HashMap<String, Integer>();
		
		//for each candidate/Max/Min, calc sum:
		for (String  candidate : optionalWinners) {
			for (String agent : agentsMinMax.keySet()) {
				minMaxCell = agentsMinMax.get(agent).getCellByCandidateName(candidate);
				addToCandidate(candidate,minMaxCell);				
			}
			//System.out.println("cand=" + candidate + this.getMax(candidate));
		}		
	}
	
	
	
	private void addToCandidate(String candidate, MinMaxCell minMaxCell) {

		Integer maxSum = candidatesMaxSum.get(candidate);
		Integer minSum = candidatesMinSum.get(candidate);
		
		if (maxSum!= null)
		{
			candidatesMaxSum.put(candidate, maxSum+minMaxCell.getMax());
		}
		else
		{
			candidatesMaxSum.put(candidate, new Integer(minMaxCell.getMax()));
		}
		
		if (minSum!= null)
		{
			candidatesMinSum.put(candidate, minSum+minMaxCell.getMin());
		}
		else
		{
			candidatesMinSum.put(candidate, new Integer(minMaxCell.getMin()));
		}
		
	}

	public int getMax(String candidate) {
		return this.candidatesMaxSum.get(candidate);
	}
	
	public int getMin(String candidate)  {
	//	if(candidate.equals("0"))
	//	  System.out.println("cand=" + candidate);
		try{
		return this.candidatesMinSum.get(candidate);
		}catch (Exception e){
			System.out.println();
			System.out.println("-----------------candidate = "+ candidate + " " + e.toString());
			return 0;
		}
	}
	
}
